package com.jcark.utilscode

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.widget.TextView

/**
 * Description:发送短信验证码工具类 <br>
 * @author King.Zi<br>
 * @date 2022/6/8<br>
 * Email: 78688689@qq.com
 */
class VerificationCodeUtil {
	
	private var allTime = 60
	private var time = allTime    // 控件倒计时
	private var TIME_MINUS = -1 // 开始倒计时
	private var TIME_IS_OUT = 0 // 结束倒计时
	private var isRunning: Boolean = true
	private lateinit var getCodeTv: TextView
	
	private var focusedColor: Int? = -1 // 运行过程中的按钮背景色值
	private var normalColor: Int? = -1 // 重新获取的按钮背景色值
	
	private var focusedTextColor: Int = Color.parseColor("#999999") // 运行过程中的文字色值
	private var normalTextColor: Int = Color.parseColor("#428EFF")  // 重新获取的文字色值
	
	constructor() {
		this.focusedColor = null
		this.normalColor = null
	}
	
	constructor(focusedColor: Int?, normalColor: Int?) {
		this.focusedColor = focusedColor
		this.normalColor = normalColor
	}
	
	fun setTextColor(focusedTextColor: Int, normalTextColor: Int) {
		this.focusedTextColor = focusedTextColor
		this.normalTextColor = normalTextColor
	}
	
	
	// 开始发送验证码 记录当前的倒计时，时间 保存发送的时间
	fun sendCode(getCodeView: TextView) {
		getCodeTv = getCodeView
		// 开启倒计时
		getCodeTv.isEnabled = false //禁用发送验证码按钮，避免重复点击
		if (focusedColor == -1 || focusedColor == null) {
			getCodeTv.setBackgroundColor(Color.parseColor("#00000000"))
			getCodeTv.setTextColor(focusedTextColor)
		} else {
			getCodeTv.setBackgroundColor(focusedColor!!)
			getCodeTv.setTextColor(normalTextColor)
		}
		
		Thread(CutDownTask()).start()
	}
	
	// 停止倒计时
	fun stopCountDown() {
		isRunning = false
	}
	
	val handler = @SuppressLint("HandlerLeak")
	object : Handler() {
		override fun handleMessage(msg: Message) {
			super.handleMessage(msg)
			when (msg.what) {
				TIME_MINUS -> {
					if (time < 10) {
						getCodeTv.text = "0$time S"
					} else {
						getCodeTv.text = "$time S"
					}
				}
				TIME_IS_OUT -> {
					getCodeTv.isEnabled = true
					getCodeTv.setTextColor(normalTextColor)
					getCodeTv.text = "重新获取"
					time = allTime
					if (normalColor == -1 || normalColor == null) {
						getCodeTv.setBackgroundColor(Color.parseColor("#00000000"))
					} else {
						getCodeTv.setBackgroundColor(normalColor!!)
					}
//					getCodeTv.setBackgroundColor(Color.parseColor("#FF7554"))
				}
			}
		}
	}

	inner class CutDownTask : Runnable {
		override fun run() {
			while (time > 0 && isRunning) {
				// 刷新剩余时间，当前子线程，使用handler
				handler.sendEmptyMessage(TIME_MINUS)
				SystemClock.sleep(1000)
				time--
			}
			handler.sendEmptyMessage(TIME_IS_OUT)
		}
	}
}